<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2015/10/29
 * Time: 15:19
 */
class MessageSearchAction extends Action{
    //消息列表
    public function messageList($serialNumber=null,$title=null,$tagId=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageSearch = M("message_search");
        $messageTagList = M("message_tag_list");
        $where['a.deleted']=array("eq",0);
        $serialNumber?$where['a.serialNumber']=array("like","%$serialNumber%"):"";
        $title?$where['a.title']=array("like","%$title%"):"";
        if($tagId){
            $where['b.tagId']=array("eq",$tagId);
            $arr = $messageTagList->alias("b")
                ->join("inner join wx_".$cid."_message_search a on b.messageId=a.id")
                ->join("wx_".$cid."_message_tag_list c on a.id=c.messageId")
                ->join("wx_".$cid."_message_tag d on c.tagId=d.id")
                ->field("a.*,group_concat(d.name) as tagName")
                ->where($where)->limit($start,$limit)
                ->group("a.id")
                ->order("a.updateTime desc")
                ->select();
            if($arr){
                $count = $messageTagList->alias("a")
                    ->join("inner join wx_".$cid."_message_search a on b.messageId=a.id")
                    ->where($where)
                    ->count();
                Output::instance()->objArray($arr,$count);
            }
        }else{
            $arr = $messageSearch->alias("a")
                ->join("wx_".$cid."_message_tag_list b on a.id=b.messageId")
                ->join("wx_".$cid."_message_tag c on b.tagId=c.id")
                ->field("a.*,group_concat(c.name) as tagName")
                ->where($where)
                ->limit($start,$limit)
                ->group("a.id")
                ->order("a.updateTime desc")
                ->select();
            if($arr){
                $count = $messageSearch->alias("a")
                    ->where($where)
                    ->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }
        }
    }
    //删除消息
    public function delMessage($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageSearch = M("message_search");
        $material = M("material");
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $messageSearch->where("id=$id")->save($data);
        if($result!==false){
            $where['module']=array("eq","messageSearch");
            $where['moduleId']=array("eq",$id);
            $where['deleted']=array("eq",0);
            $materialList = $material->where($where)->select();
            foreach($materialList as $key=>$value){
                if($value['media_id']){
                    $mdata=null;
                    $mdata['deleted']=1;
                    $mdata['updateTime']=date("Y-m-d H:i:s");
                    $result = WeixinApi::del_material($value['media_id']);
                    $result = json_decode($result,true);
                    if($result['errcode']==0){
                        $mdata['media_id']=null;
                    }else{
                        Log::write("删除永久素材失败 ".$result['errmsg']);
                    }
                    $material->where("id=".$value['id'])->save($mdata);
                }
            }
            Output::instance()->resultCode();
            return;
        }
        Output::instance()->resultCode(code_sql_error);
    }
    //获得详情
    public function getMessageInfo($id=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageSearch = M("message_search");
        $material = M("material");
        if($id){
            $result = $messageSearch->alias("a")
                ->join("wx_".$cid."_message_tag_list b on a.id=b.messageId")
                ->field("a.*,group_concat(b.tagId) as messageTag")
                ->where("a.id=$id")->find();
            $where['module']=array("eq","messageSearch");
            $where['moduleId']=array("eq",$id);
            $where['deleted']=array("eq",0);
            $where['type']=array("eq","text");
            $list =$material->where($where)->select();
            $result['texts'] = self::analysisXml($list);
            $where['type']=array(array("eq","product"),array("eq","content"),"or");
            $list=$material->where($where)->select();
            $result['materials'] = self::analysisXml($list);
            $where['type']=array("eq","image");
            $list=$material->where($where)->select();
            $result['images'] = self::analysisXml($list);
            $where['type']=array("eq","news");
            $list=$material->where($where)->select();
            $result['newsList'] = self::analysisXml($list);
            $where['type']=array("eq","audio");
            $list=$material->where($where)->select();
            $result['audios'] = self::analysisXml($list);
            $where['type']=array("eq","video");
            $list=$material->where($where)->select();
            $result['videos'] = self::analysisXml($list);
            $where['type']=array("eq","music");
            $list=$material->where($where)->select();
            $result['musics'] = self::analysisXml($list);
        }else{
            $serialNumber = $messageSearch->getField("max(serialNumber)");
            if(!$serialNumber){
                $result['serialNumber']=1000;
            }else{
                $result['serialNumber']=++$serialNumber;
            }
        }
        Output::instance()->object($result);
    }
    //解析xml
    public function analysisXml($list){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $productModel = M("module_product");
        $contentModel = M("micontent");
        Session::switchCustomer($cid);
        $materialModel = M("material");
        $result = [];
        foreach($list as $key=>$value){
            $data=[];
            $data['id'] = $value['id'];
            $data['updateTime'] = $value['updateTime'];
            $data['type'] = $value['type'];
            $xml = simplexml_load_string($value['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
            $content = $xml->message->item;
            switch($value['type']){
                case "text":
                    $str = (String)$content->content;
                    if($str == base64_encode(base64_decode($str))){
                        $str = base64_decode($str);
                    }
                    $data['content']=$str;
                    break;
                case "news":
                    $newsId = (String)$content->newsId;
                    $data["newsid"]=$newsId;
                    $data['xml']=$materialModel->where("id=$newsId")->getField("xml");
                    break;
                case "product":
                    $materialId = (String)$content->materialId;
                    $data['materialid'] = $materialId;
                    $data['typeName'] = '商品';
                    $data['name']=$productModel->where("id=$materialId")->getField("name");
                    break;
                case "content":
                    $materialId = (String)$content->materialId;
                    $data['materialid'] = $materialId;
                    $data['typeName'] = "文章";
                    $data['name']=$contentModel->where("id=$materialId")->getField("title");
                    break;
                case "image":
                    $data['imageUrl'] = (String)$content->imageUrl;
                    break;
                case "audio":
                    $data['audioUrl'] = (String)$content->audioUrl;
                    break;
                case "video":
                    $data['videoUrl'] = (String)$content->videoUrl;
                    break;
                case "music":
                    $data['musicUrl'] = (String)$content->musicUrl;
                    $data['imageUrl'] = (String)$content->imgUrl;
                    break;
            }
            $result[]=$data;
        }
        return $result;
    }
    //保存消息
    public function saveSessage($id=null,$title=null,$serialNumber=null,$messageTags=null,$textList=null,$newsList=null,$materialList=null,
                                $imageList=null,$audioList=null,$videoList=null,$musicList=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageSearch = M("message_search");
        $messageTagList = M("message_tag_list");
        $time = date("Y-m-d H:i:s");
        $searchData['title']=$title;
        $searchData['serialNumber']=$serialNumber;
        $searchData['updateTime']=$time;
        if($id){
            $messageResult = $messageSearch->where("id=$id")->save($searchData);
        }else{
            $repeatNumber = $messageSearch->where("serialNumber = '$serialNumber' and deleted=0")->find();
            if($repeatNumber){
                Output::instance()->resultCode(1,"编码重复！");
                return;
            }
            $searchData['createTime']=$time;
            $messageResult = $messageSearch->add($searchData);
            $id=$messageResult;
        }
        if($messageTags){
            $messageTagList->where("messageId=$id")->delete();
            $messageTags=explode(",",$messageTags);
            foreach($messageTags as $key=>$value){
                $data = null;
                $data['messageId']=$id;
                $data['tagId']=$value;
                $messageTagList->add($data);
            }
        }
        self::setMaterial($textList,$id,$title,"text");
        self::setMaterial($newsList,$id,$title,"news");
        self::setMaterial($materialList,$id,$title,"material");
        self::setMaterial($imageList,$id,$title,"image");
        self::setMaterial($audioList,$id,$title,"audio");
        self::setMaterial($videoList,$id,$title,"video");
        self::setMaterial($musicList,$id,$title,"music");
        Output::instance()->resultCode();
    }
    //修改素材
    public function setMaterial($list,$id,$title,$type){
        $material = M("material");
        $time = date("Y-m-d H:i:s");
        $list = json_decode($list,true);
        foreach($list as $key=>$text){
            $data=null;
            $maId = $text['id'];
            $deleted = $text['deleted'];
            $imgDeleted = $text['imgDeleted'];
            if($deleted){
                $data['deleted']=1;
                $data['updateTime']=$time;
                $media_id = $material->where("id=$maId")->getField("media_id");
                if($media_id){
                    $result = WeixinApi::del_material($media_id);
                    $result = json_decode($result,true);
                    if($result['errcode']==0){
                        $data['media_id']=null;
                    }else{
                        Log::write("删除永久素材失败 ".$result['errmsg']);
                    }
                }
                $material->where("id=$maId")->save($data);
            }else if($imgDeleted){
                $data['updateTime']=$time;
                $data['xml']=$text['xml'];
                $media_id = $material->where("id=$maId")->getField("media_id");
                if($media_id){
                    $result = WeixinApi::del_material($media_id);
                    $result = json_decode($result,true);
                    if($result['errcode']==0){
                        $data['media_id']=null;
                    }else{
                        Log::write("删除永久素材失败 ".$result['errmsg']);
                    }
                }
                $material->where("id=$maId")->save($data);

            }else if($maId){
                $data['name']=$title;
                $data['updateTime']=$time;
                $data['xml']=$text['xml'];
                if($type=='text'){
                    $xml = simplexml_load_string($text['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
                    $content = $xml->message->item;
                    $str = base64_encode((String)$content->content);
                    $data['xml']="<xml><message><item><content><![CDATA[$str]]></content></item></message></xml>";
                }
                $material->where("id=$maId")->save($data);
            }else{
                $data['name']=$title;
                $data['moduleId']=$id;
                $data['module']="messageSearch";
                $data['updateTime']=$time;
                if($type=='material'){
                    $data['xml']=$text['xml'];
                    $data['type']=$text['type'];
                }else if($type=='text'){
                    $xml = simplexml_load_string($text['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
                    $content = $xml->message->item;
                    $str = base64_encode((String)$content->content);
                    $data['xml']="<xml><message><item><content><![CDATA[$str]]></content></item></message></xml>";
                    $data['type']=$type;
                }else{
                    $data['xml']=$text['xml'];
                    $data['type']=$type;
                }
                $material->add($data);
            }
        }
    }
    //查询消息人员
    public function getMessageAdmin($nickname=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageAdmin = M("message_admin");
        $condition['a.deleted']=array("eq",0);
        $nickname?$condition['b.nickname']=array("like","%$nickname%"):"";
        $arr = $messageAdmin->alias("a")
            ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.id")
            ->where($condition)
            ->field("a.id,a.admin,b.nickname,b.headimgurl,a.createTime")
            ->limit($start,$limit)
            ->select();
        if($arr){
            $count = $messageAdmin->alias("a")
                ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.id")
                ->where($condition)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //删除管理人员
    public function delMessageAdmin($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageAdmin = M("message_admin");
        $result = $messageAdmin->where("id=$id")->setField("deleted",1);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    public function addMessageAdmin($ids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageAdmin = M("message_admin");
        $weixinInfo = M("user_weixin_info");
        $ids = explode(",",$ids);
        $where['id']=array("in",$ids);
        $usersInfo = $weixinInfo->where($where)->field("id,openid")->select();
        $time = date("Y-m-d H:i:s");
        foreach($usersInfo as $key=>$value){
            $data=null;
            $data['userId']=$value['id'];
            $data['openid']=$value['openid'];
            $data['createTime']=$time;
            $messageAdmin->add($data);
        }
        Output::instance()->resultCode();
    }
    //保存配置
    public function saveMessageConfig($addStr,$editStr,$delStr,$xml=''){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $materialModel = M("material");
        $keywordMaterial = M("material_keyword");
        $id = $materialModel->where("module='messageSearch' and type='config'")->getField("id");
        $data['xml']=$xml;
        $data['updateTime']=date("Y-m-d H:i:s");
        if(!$id){
            $data['module']='messageSearch';
            $data['name']='messageSearchConfig';
            $data['type']='config';
            $id = $materialModel->add($data);
        }else{
            $materialModel->where("id=$id")->save($data);
        }
        $keywordMaterial->where("materialId=$id")->setField("deleted",1);
        $keys=array();
        array_push($keys,$addStr,$editStr,$delStr);
        $matchs = array();
        array_push($matchs,1,1,1);
        R("MaterialKeyword/addData",array($id,implode(",",$keys),implode(",",$matchs)));
        Output::instance()->resultCode();
    }
    //获得message配置
    public function getMessageConfig(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $materialModel = M("material");
        $materialInfo = $materialModel->where("module='messageSearch' and type='config'")->getField("xml");
        $xml = simplexml_load_string($materialInfo,'SimpleXMLElement', LIBXML_NOCDATA);
        $content = $xml->message->item;
        $result['addStr']=(String)$content->addStr;
        $result['editStr']=(String)$content->editStr;
        $result['delStr']=(String)$content->delStr;
        $result['openWhileList']=(String)$content->openWhileList;
        Output::instance()->object($result);
    }
    //查询记录
    public function searchHistoryList($nickname=null,$content=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $messageHistory = M("message_search_history");
        Session::switchCustomer($cid);
        $where['a.cid'] = $cid;
        $content?$where["a.content"]=array("like","%$content%"):"";
        $nickname?$where['b.nickname']=array("like","%$nickname%"):"";
        $arr = $messageHistory->alias("a")
            ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.userId")
            ->field("a.id,a.content,a.createTime,b.nickname,b.headimgurl")
            ->where($where)
			->order("a.createTime desc")
            ->select();
        if($arr){
            $count = $messageHistory->alias("a")
                ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.userId")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    //标签
    public function getMessageTags(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageTag = M("message_tag");
        $arr = $messageTag->field("id,name as tagName")->select();
        if($arr){
            $count = $messageTag->count();
            Output::instance()->objArray($arr,$count);
            return;
        }
        Output::instance()->resultCode();
    }
    //新增标签
    public function addMessageTag($name){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageTag = M("message_tag");
        $result = $messageTag->add(['name'=>$name]);
        if($result){
            $result['id']=$result;
            Output::instance()->object($result);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //权限管理
    public function setMessageAdmin($id,$admin){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $adminMessage = M("message_admin");
        $result = $adminMessage->where("id=$id")->setField("admin",$admin);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //操作日志
    public function operationLog($id,$nickname=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer($cid);
        $messageLog = M("message_log");
        $where['a.module']=array("eq","messageSearch");
        $where['a.moduleId']=array("eq",$id);
        $nickname?$where['b.nickname']=array("like","%$nickname%"):"";
        $arr = $messageLog->alias("a")
            ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.id")
            ->where($where)
            ->field("a.id,b.nickname,b.headimgurl,a.createTime")
            ->limit($start,$limit)
            ->select();
        if($arr){
            $count = $messageLog->alias("a")
                ->join("inner join wx_".$cid."_user_weixin_info b on a.userId=b.id")
                ->where($where)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }

}